package com.uestc.shop.web;

import com.uestc.shop.base.ApiResponse;
import com.uestc.shop.domain.Product;
import com.uestc.shop.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Package: com.uestc.shop.web
 * @author: Jounghu
 * @date: 2018/7/26 21:24
 * @version: V1.0
 */
@Controller
public class SearchController {


    @Autowired
    IProductService productService;

    @GetMapping("/search")
    public String listAll(@RequestParam(defaultValue = "10") int size, @RequestParam(defaultValue = "0") int page, String keywords, HttpServletRequest request) {


        Page<Product> result = productService.search(page, size, keywords);
        long totalElements = result.getTotalPages();
        List<Product> products = new ArrayList<>();
        Iterator<Product> iterator = result.iterator();
        while (iterator.hasNext()) {
            products.add(iterator.next());
        }
        request.setAttribute("total", totalElements);
        if (products.size() == 0) {
            request.setAttribute("noMsg", 1);
        }

        // 这里判断一下，如果没有数据，显示没有
        request.setAttribute("page", page + 1);
        request.setAttribute("keywords", keywords);
        request.setAttribute("products", products);
        return "result";
    }

}
